package com.mjt.dongbao.common.base.exceptionHandle;

import com.mjt.dongbao.common.base.result.ResultWrapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;

/**
 * @Description: 对于参数校验不通过的统一异常处理
 * @Author mjt
 * @Time 2021/12/31
 */
@ControllerAdvice
public class ValidateHandler extends ResponseEntityExceptionHandler {

    /**
     *
     * @Description: 处理校验参数异常
     * @Author mjt
     * @Date 2022/1/13
     */
    @Override
    public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                               HttpHeaders headers,
                                                               HttpStatus status,
                                                               WebRequest request){

        StringBuilder stringBuilder = new StringBuilder();

        // 获取参数绑定的异常信息
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();

        // 遍历所有的异常信息
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            // 异常信息的拼接
            stringBuilder.append("提交的数据不符合规则：" + defaultMessage);

            // 在此处 break 的含义是：一旦出现了首个校验异常，就直接跳出循环不再遍历后续的异常
            break;
        }

        // 返回封装好的异常结果
        return new ResponseEntity<>(ResultWrapper.builder().code(102).msg(stringBuilder.toString()).build(),
                HttpStatus.OK);
    }



}
